const CommonApi = require('../../../api/common.js');
const UserApi = require('../../../api/user.js');
const regExpUtil = require('../../utils/regExp.js');

Page({
  data: {
    tickTip: '获取验证码',
    dialogVisible: false,
    // formModel--start
    phoneNumber: null,
    code: null,
    codeId: null,
    captcha: null,
    captchaId: null,
    // formModel--end
    redirect_uri: '/pages/index/index',
    redirect_uri_type: 'tab',
    msgSend: false,
    isAgree: false,
    timers: 60,
    countDown: null,
  },

  onLoad(options) {
    if (options.redirect_uri) {
      this.setData({redirect_uri: options.redirect_uri})
    }
    if (options.redirect_uri_type) {
      this.setData({redirect_uri_type: options.redirect_uri_type})
    }
  },

  onReady() {},
  onShow() {},
  onHide() {},
  handleInput(e){
    let target = e.currentTarget.dataset.item;
    let value = e.detail.value;
    if (target == 'phoneNumber') {
      this.setData({phoneNumber: value})
    } else if (target == 'code') {
      this.setData({code: value})
    }
  },
  checkboxChange(e){
    let value = e.detail.value;
    this.setData({isAgree: value.length > 0})
  },
  startInterval(){
    let that = this;
    let countDownNum = that.data.timers;

    that.data.countDown = setInterval(()=>{
      if (countDownNum < 1) {
        that.setData({tickTip: '获取验证码', timers: 60});
        clearInterval(that.data.countDown);
      } else {
        countDownNum--;
        that.setData({
          timers: countDownNum,
          tickTip: countDownNum+'s后重发'
        })
      }
    }, 1000)
  },
  getVerifyCode(){
    if (this.data.tickTip != '获取验证码') return;
    if (!this.data.phoneNumber) {
      wx.showToast({icon: 'none', title: '请输入手机号码'})
    } else if (this.data.phoneNumber && !regExpUtil.isPhoneNumber(this.data.phoneNumber)) {
      wx.showToast({icon: 'none', title: '请输入正确的手机号码'})
    } else {
      this.setData({dialogVisible: true});
    }
  },
  // 获取图形验证码弹窗传递来的数据
  getCaptchaData(e){
    console.log(e);
    this.setData({
      dialogVisible: false, 
      captcha: e.detail.captcha,
      captchaId: e.detail.captchaId
    })
    this.sendRegisterSms()
  },
  // 关闭图形验证码弹窗
  closeModal(){
    this.setData({
      dialogVisible: false, 
    })
  },
  // 发送注册验证码
  sendRegisterSms(){
    CommonApi.sendRegisterSms({phoneNumber: this.data.phoneNumber, code: this.data.captcha, captchaId: this.data.captchaId}).then(res=>{
      if (res.retCode == "000000" && res.errCode == "000000") {
        this.setData({msgSend: true, codeId: res.data});
        wx.showToast({icon: 'success', title: '发送验证码成功'});
        this.startInterval();
      }
    })
  },
  // 校验短信验证码
  checkSms(){
    CommonApi.checkSms({phoneNumber: this.data.phoneNumber, code: this.data.code, codeId: this.data.codeId}).then(res=>{
      if (res.retCode == '000000' && res.errCode == '000000') {
        console.log(res);
        if (!res.data) {
          wx.showToast({icon: 'error', title: '验证码错误'});
        } else {
          this.submitForm()
        }
      } else {
        wx.showToast({icon: 'error', title: '验证码错误'});
      }
    })
  },
  submitForm(){
    if (!this.data.isAgree) {
      wx.showToast({icon: 'none', title: '请勾选阅读并接受用户协议'})
    } else {
      let formModel = {code: this.data.code, codeId: this.data.codeId, phoneNumber: this.data.phoneNumber, sourceSite: 'quotation', loginFrom: 'xcx'};
      CommonApi.phoneRegister({...formModel}).then(res=>{
        if (res.retCode == "000000" && res.errCode == "000000") {
          let expires = new Date(new Date() * 1 + res.data.expiresIn * 1000)
          wx.showToast({icon: 'success', title: '注册成功'});

          wx.setStorageSync('token', res.data.accessToken);
          wx.setStorageSync('tokenExpire', expires) // 记录token有效期限(毫秒值)
          wx.setStorageSync('lastLoginInfo', {phoneNumber: this.data.phoneNumber});

          UserApi.getLoginUser().then(userRes=>{
            if (userRes.retCode == "000000" && userRes.errCode == "000000") {
              wx.setStorageSync('userInfo', userRes.data)
              if (this.data.redirect_uri_type == 'tab') {
                wx.switchTab({url: this.data.redirect_uri})
              } else if (this.data.redirect_uri_type == 'link') {
                wx.redirectTo({url: this.data.redirect_uri})
              }
            }
          })
        } else {
          wx.showToast({icon: 'error', title: res.errMsg});
        }
      })
    }
  },
  formSubmit(e){
    console.log(e.detail.value);
    if (!this.data.phoneNumber) {
      wx.showToast({icon: 'none', title: '请输入手机号码'})
    } else if (this.data.phoneNumber && !regExpUtil.isPhoneNumber(this.data.phoneNumber)) {
      wx.showToast({icon: 'none', title: '请输入正确的手机号码'})
    } else if (!this.data.code) {
      wx.showToast({icon: 'none', title: '请输入验证码'})
    } else if (this.data.code && this.data.code.length!=6) {
      wx.showToast({icon: 'none', title: '请输入正确的验证码'})
    } else if (!this.data.isAgree) {
      wx.showToast({icon: 'none', title: '请勾选阅读并接受用户协议'})
    } else {
      this.checkSms();
    }
  },
  checkProtocol(){
    wx.navigateTo({
      url: '/packageA/pages/protocol/index',
    })
  },
  toLogin(){
    wx.redirectTo({
      url: '/packageA/pages/login/index?redirect_uri='+this.data.redirect_uri+'&redirect_uri_type='+this.data.redirect_uri_type,
    })
  },
  getUserProfile() {
    wx.getUserProfile({
      desc: '用于完善会员资料', // 声明获取用户个人信息后的用途，后续会展示在弹窗中，请谨慎填写
      success: (res) => {
        console.log(res);
        wx.login({
          success: (loginRes) => {
            console.log(loginRes);
            this.xcxLogin(loginRes.code)
          },
        })
      }
    })
  },
  xcxLogin(code){
    let that = this;
    CommonApi.xcxLogin({code: code}).then(res=>{
      console.log(res);
      if (res.retCode == "000000" && res.errCode == "000000") {
        if (!res.data.accessToken) {
          wx.navigateTo({
            url: '/packageA/pages/bindRegister/index?registerId='+res.data.registerId+'&redirect_uri_type='+that.data.redirect_uri_type+'&redirect_uri='+that.data.redirect_uri,
          })
        } else {
          let expires = new Date(new Date() * 1 + res.data.expiresIn * 1000)
          wx.setStorageSync('token', res.data.accessToken);
          wx.setStorageSync('tokenExpire', expires) // 记录token有效期限(毫秒值)
          setTimeout(()=>{
            that.getLoginUser()
          }, 200)
        }
      } else {
        wx.showToast({icon: 'error', title: res.errMsg})
      }
    })
  },
  // 查询登录用户详情
  getLoginUser(){
    UserApi.getLoginUser().then(userRes=>{
      if (userRes.retCode == "000000" && userRes.errCode == "000000") {
        wx.setStorageSync('userInfo', userRes.data)
        if (this.data.redirect_uri_type == 'tab') {
          wx.switchTab({url: this.data.redirect_uri})
        } else if (this.data.redirect_uri_type == 'link') {
          wx.redirectTo({url: this.data.redirect_uri})
        }
        wx.showToast({icon: 'success', title: '登录成功'})
      }
    })
  },

  onUnload() {

  },

  onShareAppMessage() {
    return {
      title: "注册",
      path: "/packageA/pages/register/index",
    }
  },

  onShareTimeline() {
    return {
      title: "注册",
    }
  }
})